import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {messageWarning} from '@/utils/commonUtil'
import {i18n, loadDynamicLang} from '@/lang'
import {useTitle} from '@vueuse/core'
import {Local, Session} from '@/utils/storageUtil'
import {generateRoutes} from '@/utils/routeUtil'
import {cacheKeys} from '@/stores/constant/cacheKey'
import {useUserStore} from '@/stores/modules/user.store'

// 进度条配置
NProgress.configure({showSpinner: false})

// 无需登录即可访问的路由
const whiteList = [
	'/login',
	'/modifyPassword',
	'/forgetPassword',
	'/activateEmail',
	'/modifyEmail',
	'/401',
	'/404'
]

router.beforeEach(async (to, from, next) => {

	// 进度条
	NProgress.start()

	// 切换页面标题
	const title = useTitle()
	const pageTitle = i18n.global.t(<string>to.meta.title)
	const siteName = i18n.global.t('siteName')
	title.value = `${pageTitle || i18n.global.t('noTitle')}${siteName ? ' - ' + siteName : ''}`

	// 判断是否登录
	const token = Local.get(cacheKeys.TOKEN)
	if (token) {
		// 加载动态路由
		const routerInit = Session.get(cacheKeys.ROUTER_INIT)
		if (!routerInit) {
			generateRoutes()
			if (to.redirectedFrom) {
				next({path: to.redirectedFrom.path, query: to.redirectedFrom.query})
			} else {
				if (to.path === '/login') {
					messageWarning(i18n.global.t('login.loggedIn'))
					next({path: from.path, query: from.query})
				} else {
					loadDynamicLang(to.path)
					next({path: to.path, query: to.query})
				}
			}
		} else {
			// 检查token是否过期
			const expire = Local.get(cacheKeys.EXPIRE)
			if (!expire || new Date(expire).getTime() < new Date().getTime()) {
				await useUserStore().logout()
				Local.remove(cacheKeys.TOKEN)
				messageWarning(i18n.global.t('login.expired'))
				// 如果携带路径参数注销，则loginTo使用fullPath，否则使用path
				// next({path: '/login', query: {loginTo: to.fullPath}})
				next({path: '/login', query: {loginTo: to.path}})
				return
			}
			if (to.path === '/login') {
				messageWarning(i18n.global.t('login.loggedIn'))
				next({path: from.path, query: from.query})
			} else {
				loadDynamicLang(to.path)
				next()
			}
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			loadDynamicLang(to.path)
			next()
		} else {
			messageWarning(i18n.global.t('login.loginFirst'))
			let loginTo = to.redirectedFrom?.path ?? to.path
			if (loginTo === '/login') {
				loginTo = '/'
			}
			next(`/login?loginTo=${loginTo}`)
		}
	}
})

router.afterEach(() => {
	NProgress.done()
})
